import React, { useEffect } from 'react';
import { Icon, Tooltip } from 'antd';
import { connect } from 'dva';
import { Form, FormItem, createFormActions, FormEffectHooks } from '@formily/antd';
import { Input, Radio, Switch, Select, Range, NumberPicker } from '@formily/antd-components';
import classNames from 'classnames';
import throttle from 'lodash/throttle';
import omit from 'lodash/omit';
import has from 'lodash/has';
import get from 'lodash/get';
import { getStepMarks } from '../utils';
import styles from '../../styles.less';

const actions = createFormActions();

const { onFormInputChange$ } = FormEffectHooks;

/**
 * TODO:
 * 1、必填时，表单重置后 不会收起help信息
 * 2、上传、删除以及回参
 */
function ForSlickUpload({ dispatch, current, columnNum }) {
  useEffect(() => {
    // 清空状态
    actions.reset({ validate: false });

    // 剔除holder是冗余的key
    const keys = Object.keys(actions.getFormGraph()).filter(val => val !== '');

    // 遍历，给所有的formItem设置值
    keys.forEach(value => {
      if (has(current, value)) {
        actions.setFieldValue([value], get(current, value));
      }
    });
  }, [current]);

  return (
    <Form
      className={classNames(styles.configForm)}
      actions={actions}
      colon={false}
      effects={() => {
        // 只监控人工操作引起的FormItem值变化
        onFormInputChange$().subscribe(
          throttle(
            async () => {
              await actions.validate({ silent: true });
              // actions.getFormState().valid取到的结果是异步的，所以必须用到await actions.validate才能得到精确的结果
              const isValid = actions.getFormState().valid;

              // 校验失败
              if (!isValid) {
                return;
              }

              // 当前面板所有formitem字段的值
              let formValues = actions.getFormState().values;

              // 必填, 补充whitespace等字段
              if (get(formValues, 'rules.requiredRule.required') === true) {
                formValues = {
                  ...formValues,
                  rules: {
                    ...formValues.rules,
                    requiredRule: { required: true, whitespace: true, message: '必填项' },
                  },
                };
              }

              // required==false时剔除，（因为在reset()时 required会变成false）
              if (get(formValues, 'rules.requiredRule.required') === false) {
                formValues = {
                  ...formValues,
                  rules: omit(formValues.rules, ['requiredRule']),
                };
              }

              dispatch({
                type: 'formDesigner/updateNode',
                payload: formValues,
              });
            },
            300,
            { trailing: true, leading: false }
          )
        );
      }}
    >
      <FormItem
        label="标题"
        name="label"
        allowClear
        required
        triggerType="onChange"
        component={Input}
        placeholder="无"
        initialValue="_" // 避免在reset时触发校验
      />

      <FormItem
        label="字段名称"
        name="name"
        allowClear
        required
        disabled
        triggerType="onChange"
        component={Input}
        initialValue="_" // 避免在reset时触发校验
      />

      <FormItem
        label={
          <>
            水平跨度
            <Tooltip title="1表示占满一行">
              <Icon type="info-circle" className={styles.helpIcon} />
            </Tooltip>
          </>
        }
        style={{ width: '150px' }}
        name="megaProps.span"
        triggerType="onChange"
        min={1}
        step={1}
        max={columnNum}
        marks={getStepMarks(columnNum)}
        component={Range}
        initialValue={1}
      />

      {/* <FormItem
        label="初始值"
        name="initialValue"
        triggerType="onChange"
        component={Radio.Group}
        dataSource={
          Array.isArray(current.dataSource)
            ? current.dataSource.map(option => pick(option, ['label', 'value']))
            : []
        }
      /> */}

      <FormItem
        label="风格"
        allowClear
        name="uploadProps.listType"
        triggerType="onChange"
        component={Radio.Group}
        dataSource={[
          { label: 'text', value: 'text' },
          // { label: 'card', value: 'picture-card' },
        ]}
      />

      <FormItem
        label="上传地址(POST)"
        allowClear
        name="uploadProps.addUrl"
        triggerType="onChange"
        component={Input}
        rules={[{ required: true, whitespace: true, message: '必填项' }]}
      />

      <FormItem
        label="删除地址(GET)"
        allowClear
        name="uploadProps.deleteUrl"
        triggerType="onChange"
        component={Input}
        rules={[{ required: true, whitespace: true, message: '必填项' }]}
      />

      <FormItem
        label="最多上传"
        min={1}
        initialValue={9}
        formatter={value => `${value} 个`}
        parser={value => value.replace(' 个', '')}
        name="uploadProps.length"
        triggerType="onChange"
        component={NumberPicker}
      />

      <FormItem
        label="最大Size"
        min={0.001}
        max={999}
        initialValue={10}
        name="uploadProps.size"
        triggerType="onChange"
        formatter={value => `${value} MB`}
        parser={value => value.replace(' MB', '')}
        component={NumberPicker}
      />

      <FormItem
        label="附件格式"
        allowClear
        name="uploadProps.accept"
        triggerType="onChange"
        component={Select}
        mode="multiple"
        placeholder="选择格式"
        dataSource={[
          { label: 'jpg', value: '.jpg' },
          { label: 'png', value: '.png' },
          { label: 'gif', value: '.gif' },
          { label: 'svg', value: '.svg' },
          { label: 'txt', value: '.txt' },
          { label: 'doc/docx', value: '.doc,.docx' },
          { label: 'xls/xlsx', value: '.xls,.xlsx' },
          { label: 'ppt/pptx', value: '.ppt,.pptx' },
          { label: 'pdf', value: '.pdf' },
          { label: 'rar', value: '.rar' },
          { label: 'zip', value: '.zip' },
          { label: 'mov', value: '.mov' },
        ]}
      />

      <FormItem
        label="禁用"
        name="disabled"
        triggerType="onChange"
        component={Switch}
        initialValue={false}
      />

      <FormItem
        label="编辑"
        name="editable"
        triggerType="onChange"
        component={Switch}
        initialValue
      />

      <FormItem
        label="显示"
        name="display"
        triggerType="onChange"
        component={Switch}
        initialValue
      />

      <FormItem
        label="必填"
        name="rules.requiredRule.required"
        triggerType="onChange"
        component={Switch}
        initialValue={false}
      />
    </Form>
  );
}

export default connect(({ formDesigner }) => ({
  current: formDesigner.current,
  columnNum: formDesigner.columnNum,
}))(ForSlickUpload);
